package com.zmn.plat.business.impl.service.tariff.citygroup.item;

import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.zmn.plat.business.interfaces.service.tariff.citygroup.item.ServiceTariffCityGroupItemBService;
import com.zmn.plat.common.constant.BaseAreaConsts;
import com.zmn.plat.model.entity.area.BaseArea;
import com.zmn.plat.model.entity.service.tariff.citygroup.ServiceTariffCityGroupQuery;
import com.zmn.plat.model.entity.service.tariff.citygroup.item.ServiceTariffCityGroupItem;
import com.zmn.plat.model.vo.service.tariff.citygroup.item.ServiceTariffCityGroupItemBindVO;
import com.zmn.plat.services.interfaces.area.BaseAreaService;
import com.zmn.plat.services.interfaces.service.tariff.citygroup.item.ServiceTariffCityGroupItemService;

/**
 * @author tanbiao
 * @description
 * @since 2020/5/28 15:50
 * @modifier
 **/
@Service
public class ServiceTariffCityGroupItemBServiceImpl implements ServiceTariffCityGroupItemBService {
    @Resource
    private ServiceTariffCityGroupItemService faultCityGroupItemService;
    @Resource
    private BaseAreaService baseAreaService;

    @Override
    public List<ServiceTariffCityGroupItemBindVO> listCityCanBind(ServiceTariffCityGroupQuery query) {
        // 页面可以显示的数据
        Map<Integer, ServiceTariffCityGroupItemBindVO> selectMap = new HashMap<>();
        // 省
        List<BaseArea> baseAreaList = baseAreaService.listByParentId(BaseAreaConsts.AREA_LEVEL_ONE);
        Map<Integer, String> provinceMap = baseAreaList.stream().collect(Collectors.toMap(BaseArea::getAreaId, BaseArea::getName));
        // 城市，当前分组配置的城市+没有被相同服务分类，一级分类关联的所有城市
        List<ServiceTariffCityGroupItem> enableList = faultCityGroupItemService.listCityCanBindByGroupId(query);
        if (!CollectionUtils.isEmpty(enableList)) {
            for (ServiceTariffCityGroupItem item : enableList) {
                ServiceTariffCityGroupItemBindVO vo = selectMap.get(item.getProvinceId());
                item.setProvinceName(provinceMap.get(item.getProvinceId()));
                if (Objects.isNull(vo)) {
                    vo = new ServiceTariffCityGroupItemBindVO();
                    vo.setProvinceId(item.getProvinceId());
                    vo.setProvinceName(item.getProvinceName());
                    selectMap.put(item.getProvinceId(), vo);
                }
                vo.getAreaList().add(item);
            }
            List<ServiceTariffCityGroupItemBindVO> list = new ArrayList<>(selectMap.values());
            list.sort(Comparator.comparing(ServiceTariffCityGroupItemBindVO::getProvinceId));
            list.stream().forEach(e -> e.getAreaList().sort(Comparator.comparing(ServiceTariffCityGroupItem::getCityId)));
            return list;
        }
        return Collections.emptyList();
    }
}
